"""
OCR服务模块
提供火山引擎OCR文字识别功能
"""

import base64
import logging
from .base_service import BaseAIService

# 从火山引擎SDK导入所需模块
from volcengine.visual.VisualService import VisualService

logger = logging.getLogger(__name__)

class VolcanoOCRService(BaseAIService):
    """火山引擎OCR服务 (Volcano Engine OCR Service)."""

    def __init__(self, config: dict):
        self.ak = config.get('ak')
        self.sk = config.get('sk')
        self.region = config.get('region', 'cn-beijing')

        if not self.ak or "YOUR_ACCESS_KEY" in self.ak:
            raise ValueError("Volcano Engine Access Key is not configured.")

        # 初始化火山引擎视觉服务 (Initialize Volcano Visual Service)
        self.service = VisualService()
        self.service.set_ak(self.ak)
        self.service.set_sk(self.sk)

        logger.info("[VolcanoOCR] 服务初始化完成")

    async def analyze(self, image_bytes: bytes) -> str:
        """
        使用火山引擎OCR API识别图片中的文字

        :param image_bytes: 图片字节数据
        :return: 识别出的文字内容
        """
        try:
            image_base64 = base64.b64encode(image_bytes).decode('utf-8')
            form = {'image_base64': image_base64}

            # 使用火山引擎OCR Normal API (Use Volcano OCR Normal API)
            response = self.service.ocr_normal(form)

            if response.get('ResponseMetadata', {}).get('Error'):
                error_info = response['ResponseMetadata']['Error']
                logger.error(f"Volcano OCR API Error: {error_info}")
                raise Exception(f"OCR Service Error: {error_info.get('Message')}")

            # 解析返回的文本数据 (Parse returned text data)
            data = response.get('data', {})
            line_texts = data.get('line_texts', [])
            recognized_text = " ".join(line_texts) if line_texts else ""
            return recognized_text

        except Exception as e:
            logger.error(f"Failed to call Volcano OCR: {e}")
            raise

    def get_text_length(self, text: str) -> int:
        """获取文本长度 (Get text length)."""
        return len(text.strip())

    def get_service_info(self) -> dict:
        """获取OCR服务信息"""
        base_info = super().get_service_info()
        base_info.update({
            'provider': 'volcano_engine',
            'service_type': 'ocr',
            'region': self.region
        })
        return base_info
